import os
import time
import json
import subprocess

# Load configuration
CONFIG_FILE = "config.json"
with open(CONFIG_FILE, "r") as file:
    config = json.load(file)

HOST_IP = config["host_ip"]
STANDBY_IP = config["standby_ip"]
VIRTUAL_IP = config["virtual_ip"]
PING_INTERVAL = config["ping_interval"]

def ping(ip):
    """Ping an IP address and return True if reachable."""
    response = subprocess.run(
        ["ping", "-n", "1", ip],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    return response.returncode == 0

def assign_vip(ip):
    """Assign the virtual IP to the specified machine."""
    command = f"netsh interface ip add address \"Ethernet\" {VIRTUAL_IP} 255.255.255.0"
    subprocess.run(command, shell=True)
    print(f"Assigned VIP {VIRTUAL_IP} to {ip}.")

def remove_vip(ip):
    """Remove the virtual IP from the specified machine."""
    command = f"netsh interface ip delete address \"Ethernet\" addr={VIRTUAL_IP}"
    subprocess.run(command, shell=True)
    print(f"Removed VIP {VIRTUAL_IP} from {ip}.")

def monitor_and_failover():
    """Monitor the host and handle failover and failback."""
    current_master = "host"
    while True:
        if current_master == "host" and not ping(HOST_IP):
            print("Host is down. Switching to standby...")
            remove_vip(HOST_IP)
            assign_vip(STANDBY_IP)
            current_master = "standby"
        elif current_master == "standby" and ping(HOST_IP):
            print("Host is back online. Switching to host...")
            remove_vip(STANDBY_IP)
            assign_vip(HOST_IP)
            current_master = "host"
        else:
            print(f"Current master is {current_master}.")
        time.sleep(PING_INTERVAL)

if __name__ == "__main__":
    print("Starting VIP failover monitoring...")
    monitor_and_failover()